'use strict';

angular.module('app.granaryInfo').controller('GranaryRealtimeCtrl', function ($scope, HTTPDataService,Auths) {

    /* if(!Auths.getUser())
      {
         window.location.href=baseurls+"#/login";
      }*/ 
      $scope.user = Auths.getUser();
      $scope.selectPanelShow = false;

     if($scope.user.role == "head")
       {
         $scope.selectPanelShow =  true; 
       }
        
       function setMystyle(num,all)
       {

          for(var i=0;i<all.length;i++)
          {
              if(num == all[i].granary_num)
                {
                  if(all[i].bei == "up")
                    return 'glyphicon glyphicon-arrow-up'; 
                  else if(all[i].bei == "down")
                    return 'glyphicon glyphicon-arrow-down';  
                  else if(all[i].bei == "left") 
                     return 'glyphicon glyphicon-arrow-left';
                   else if(all[i].bei == "right") 
                     return 'glyphicon glyphicon-arrow-right';
                   else
                     return 'glyphicon glyphicon-arrow-right';


                }

          }
       
       }
      //转到报表页面

      $scope.allreport = function(){

         window.location.href=baseurls+"#/granaryInfo";

       }

        //系统数据
       HTTPDataService.getSystemConfig().then(function(response){
          
           $scope.systemDate = response;
          
           var high_t = parseInt($scope.systemDate.high_t_threshold);
           var low_t = parseInt($scope.systemDate.low_t_threshold);
           $scope.setStyle = function(point_t) { 

              
              if(point_t > high_t)  
                return 'badge bg-color-red'; 
              else if(point_t < low_t)
                return 'badge bg-color-blueLight';  
              
              else  
                return '';   
              };
 
        });
      
      var GranaryDe = HTTPDataService.getGranaryDetail(); 
       $scope.temparray =  new Array();
      $scope.lan =0;
       HTTPDataService.getGranaryAll_v().then(function(response) {
     
       $scope.granaryData = response;

       if(GranaryDe)
         {
           $scope.currentGranaryNumber = GranaryDe;
         }
       else
         {
           $scope.currentGranaryNumber = '11F';
         }


        $scope.mystyle = setMystyle($scope.currentGranaryNumber,$scope.granaryData);  
     
         //最近的20个温度 
            HTTPDataService.getlately_avg($scope.currentGranaryNumber).then(function(responses){
            
               $scope.liveStats = responses;
            
              })
        
           
          //每天都会更新的数据
        HTTPDataService.getGranaryData($scope.currentGranaryNumber).then(function(response){
          
          $scope.granaryRealtimeData = response['lastrealdata'];
        

       //立体模型的数据
     
       var  laydata = $scope.granaryRealtimeData.all_t;
       $scope.dataArray = new Array();
        for(var i=0;i<laydata.length;i++)
         {
           $scope.dataArray.push(laydata[i].level);      
         } 
        if(paper)
           paper.remove(); 
        draws($scope.dataArray); 
       
            var counts = 0;

           for(var i=0;i<$scope.dataArray[0][0].length;i++)
            {   
              var temparrays = new Array();
               var count = new Array();   
                   for(var j=0;j<$scope.dataArray[0].length;j++) 
                     {
                           counts = counts + 1;
                           count.push([counts+'缆',2]);
                         
                      }
                  temparrays.push(count)
              for(var z=0;z<$scope.dataArray.length;z++)
              {
                  var ceng =new Array();
                 for(var j=0;j<$scope.dataArray[0].length;j++) 
                     {
                           ceng.push($scope.dataArray[z][j][i]);
                         
                      }
                
                 temparrays.push(ceng)
                   
              }


            $scope.temparray.push(temparrays)

            }
        
      
        });
        
       });
                
        
        //最近20个平均温度
          

          

       $scope.liveStats = [[[0,50],[1,45],[2,35],[4,55],[5,76],[7,88],[7,80]]];
        

         $scope.tabActive="active";
         $scope.changeGranary = function(granaryNumber){
           $scope.lan =0;
         $scope.tabActive="active";
         $scope.currentGranaryNumber = granaryNumber;
         $scope.mystyle = setMystyle($scope.currentGranaryNumber,$scope.granaryData);
        //最近的20个温度 
        HTTPDataService.getlately_avg(granaryNumber).then(function(responses){
            
               $scope.liveStats = responses;
            
             })
       //每天都会更新的数据
       HTTPDataService.getGranaryData(granaryNumber).then(function(response){
         
          $scope.granaryRealtimeData = response['lastrealdata'];

          //console.log($scope.granaryRealtimeData);
             //立体模型的数据
       
        if(paper)     
        paper.remove();   
        var laydata = $scope.granaryRealtimeData.all_t;
        $scope.dataArray = new Array();
        for(var i=0;i<laydata.length;i++)
         {
           $scope.dataArray.push(laydata[i].level);      
         } 
          draws($scope.dataArray);  

         
         
        var counts = 0;
       $scope.temparray = new Array();


           for(var i=0;i<$scope.dataArray[0][0].length;i++)
            {   
              var temparrays = new Array();
               var count = new Array();   
                   for(var j=0;j<$scope.dataArray[0].length;j++) 
                     {
                           counts = counts + 1;
                           count.push([counts+'缆',2]);
                         
                      }
                  temparrays.push(count)
              for(var z=0;z<$scope.dataArray.length;z++)
              {

                  var ceng =new Array();
                 for(var j=0;j<$scope.dataArray[0].length;j++) 
                     {
                           ceng.push($scope.dataArray[z][j][i]);
                         
                      }
                
                 temparrays.push(ceng)
                   
              }


            $scope.temparray.push(temparrays)

            }
        
       
        
         })
        
        
      };
   
   
          
  //按线缆查看，导出excel
    $scope.exportData = function () {

        var blob = new Blob(["\ufeff" +document.getElementById('exportable').innerHTML+document.getElementById('exportable2').innerHTML+document.getElementById('exportable3').innerHTML], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
        });
        
        saveAs(blob, "Report.xls");
    };

  //按层查看,
   
    $scope.s2Excel = function(){
       
        var blob = new Blob(["\ufeff" +document.getElementById('s2Excel').innerHTML + document.getElementById('layer2').innerHTML], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
        });
        saveAs(blob, "repost.xls");
     };

  
var paper;

   function draws(dataArray) {
     
    if (dataArray.length <= 0) return;
    var li = [dataArray[0][0].length, dataArray[0].length]; //列数，行数
    var n = dataArray.length; //层数

    var width = 150 * li[0]; //宽度
    if (width < 600) width = 600;
    var height = n * 150; //高度
    var wn = 2;//暂时不用，暂定为初始化显示层数
    var l = [40, 10]; //距离边距，[左,上]
    var q = 45; //角度
    var lh = height / n - 5; //景深
    var lw = lh / (Math.tan(q * 2 * Math.PI / 360)); //景宽
    var mw = width - 2 * lw; //内宽度
    Raphael.el.DataArray = function(ec) {
        this.dataArray = ec;
        return this;
    };
    paper = Raphael("drawContent");//画板
    paper.setSize(width + l[0] * 2+60, height + 2 * l[1] + 200); //设置画布大小

    function init() {
        var stSeting = paper.set(); //绘制背景
        stSeting.push(
                    paper.rect(l[0] + lw, l[1], mw, height).DataArray(1), //正背景
                    paper.path("M" + (l[0] + lw) + " " + l[1] + "L" + l[0] + " " + (l[1] + lh) + "V" + (l[1] + lh + height) + "L" + (l[0] + lw) + " " + (l[1] + height) + ""), //左背景
                    paper.path("M" + (l[0] + lw + mw) + " " + l[1] + "L" + (l[0] + width) + " " + (l[1] + lh) + "V" + (l[1] + lh + height) + "L" + (l[0] + lw + mw) + " " + (l[1] + height) + "")//右背景
                );
        stSeting.attr({ "fill": "90-#fff-#000", "fill-opacity": "0.1" }); //背景属性,填充渐变，0.1透明
        var stFont = paper.set(); //绘制背景
        stFont.push(paper.text(l[0] + width + 10, 30, "" + ""),
                     paper.text(l[0] + width + 10, 60, "" + ""),
                     paper.text(l[0] + width + 10, 90, "" + ""),
                     paper.text(l[0] + width + 10, 120, "" + ""),
                     paper.text(l[0] + width + 10, 150, "" +"" ));     
        stFont.attr({ "text-anchor": "start", "font": "11px 宋体, Arial", "stroke": "#000" });
        
        var stWall = paper.set(); //绘制墙
        for (var i = 0; i < n; i++) {
            var _x = l[0] + lw;//x轴坐标
            var _y = l[1] + lh * (i + 1) + 5 * i; //y轴坐标
            stWall.push(paper.path([["M", _x, _y], ["L", (_x + mw), _y], ["L", l[0] + width, _y + lh], ["L", l[0], _y + lh], ["L", _x, _y]])); //绘制平行四边形墙
            //drawDian(i);
            paper.text(10, _y + 40,  (i+1) + "层").attr({ "stroke": "#000", "font": "12px 宋体, Arial" });
        }
        stWall.attr({ "fill": "#F7E39A", "fill-opacity": "0.3", "cursor": "pointer" }).mouseout(function(event) {//墙的属性
            this.animate({ "fill-opacity": "0.3" }, 1000); //鼠标移出事件
        }).mouseover(function(event) {
            this.animate({ "fill-opacity": "1" }, 1000); //鼠标移入事件
        });

        var seLine = paper.set();//绘制线
        for (var i = 0; i < n; i++) {
            for (var _x = 0; _x < li[0] + 1; _x++) {//竖线
                seLine.push(paper.path([["M", (l[0] + lw + mw / (li[0] + 1) * _x), (l[1] + lh * (i + 1) + 5 * i)], ["L", (l[0] + width / (li[0] + 1) * _x), (l[1] + 5 * i + lh * (i + 2))]]));
            }
            for (var _y = 0; _y < li[1] + 1; _y++) {//横线
                seLine.push(paper.path([["M", (l[0] + lw / (li[1] + 1) * _y), (l[1] + lh * 2 - lh / (li[1] + 1) * _y + lh * i + 5 * i)], ["L", (l[0] + width - lw / (li[1] + 1) * _y), (l[1] + lh * 2 - lh / (li[1] + 1) * _y + lh * i + 5 * i)]]));
            }
        }
        seLine.attr({ "stroke": "rgba(0,0,128)" });

        for (var j = 0; j < n; j++) {//绘制点，层循环
            for (var jj = 0; jj < li[0]; jj++) {//列循环
                for (var jjj = 0; jjj < li[1]; jjj++) {//行循环
                    if (dataArray[j][jjj][jj][0] > -50 && dataArray[j][jjj][jj][0] < 50) {
                        var _xx = l[0] + lw / (li[1] + 1) * (li[1] - jjj) + (width - lw / (li[1] + 1) * (li[1] - jjj) * 2) / (li[0] + 1) * (jj + 1); //圆心坐标x轴
                        var _yy = (j + 1) * (lh + 5) + lh / (li[1] + 1) * (jjj + 1) + 4; //圆心坐标y轴
                       
                        if(dataArray[j][jjj][jj][1] == 3)
                         {
                          paper.circle(_xx, _yy, 4).attr({ "fill": dataArray[j][jjj][jj][1] == 3 ? "rgba(225,0,0)" : "50-#fff-#000", "fill-opacity": "10", "cursor": "pointer", "title": dataArray[j][jjj][jj][0] }); //绘制圆点   
                          paper.text(_xx + 47, _yy + 8, (dataArray[j][jjj][jj][0]+'('+(li[1]-jjj)+','+(jj+1)+')')).attr({ "stroke": "rgba(255,0,0)", "font": "14px 宋体, Arial" }); //绘制数据 
                         }
                          
                         
                        else if(dataArray[j][jjj][jj][1] == 4)
                         {
                             paper.circle(_xx, _yy, 4).attr({ "fill": dataArray[j][jjj][jj][1] == 4 ? "rgba(255,165,0)" : "50-#fff-#000", "fill-opacity": "10", "cursor": "pointer", "title": dataArray[j][jjj][jj][0] }); //绘制圆点   
                             paper.text(_xx + 47, _yy + 8, (dataArray[j][jjj][jj][0]+'('+(li[1]-jjj)+','+(jj+1)+')')).attr({ "stroke": "rgba(220,20,60)", "font": "14px 宋体, Arial" }); //绘制数据
                         }
                        
                      else if(dataArray[j][jjj][jj][1] == 5)
                        {
                           paper.circle(_xx, _yy, 4).attr({ "fill": dataArray[j][jjj][jj][1] == 5 ? "rgba(0,128,0)" : "50-#fff-#000", "fill-opacity": "5", "cursor": "pointer", "title": dataArray[j][jjj][jj][0] }); //绘制圆点
                           paper.text(_xx + 47, _yy + 8, (dataArray[j][jjj][jj][0]+'('+(li[1]-jjj)+','+(jj+1)+')')).attr({ "stroke": "rgba(0,128,0)", "font": "14px 宋体, Arial" }); //绘制数据
                        }
                        
                        
                       else
                       {
                         paper.circle(_xx, _yy, 4).attr({ "fill": dataArray[j][jjj][jj][1] == 3 ? "rgba(225,0,0)" : "50-#fff-#000", "fill-opacity": "1", "cursor": "pointer", "title": dataArray[j][jjj][jj][0] }); //绘制圆点
                         paper.text(_xx + 18, _yy + 8,dataArray[j][jjj][jj][0]).attr({ "stroke": "rgba(0,0,255)", "font": "14px 宋体, Arial" }); //绘制数据
                       }
                        
                    }
                    else if (dataArray[j][jjj][jj][0] != 1001) {//如果不是正常范围的值，且也不是1001，则显示异常  李辉 2011-9-30
                        var _xx = l[0] + lw / (li[1] + 1) * (li[1] - jjj) + (width - lw / (li[1] + 1) * (li[1] - jjj) * 2) / (li[0] + 1) * (jj + 1); //圆心坐标x轴
                        var _yy = (j + 1) * (lh + 5) + lh / (li[1] + 1) * (jjj + 1) + 4; //圆心坐标y轴
                        paper.circle(_xx, _yy, 4).attr({ "fill": dataArray[j][jjj][jj][1] == 3 ? "rgba(225,0,0)" : "50-#fff-#000", "fill-opacity": "1", "cursor": "pointer", "title": '异常' }); //绘制异常点
                        paper.text(_xx + 36, _yy + 8, '故障('+(li[1]-jjj)+','+(jj+1)+')').attr({ "stroke": "rgba(0,0,0)", "font": "14px, Arial" }); //绘制数据
                    }//如果温度值==1001，则说明该点没有布测温点，什么都不绘制
                }
            }
        }
    }
    init();
}



       
    $scope.liveStatsOptions = {
        yaxis: {
            min: -10,
            max: 10
        },
        xaxis: {
            min: 0,
            max: 100
        },
        colors: ['rgb(87, 136, 156)'],
        series: {
            lines: {
                lineWidth: 1,
                fill: true,
                fillColor: {
                    colors: [
                        {
                            opacity: 0.4
                        },
                        {
                            opacity: 0
                        }
                    ]
                },
                steps: false
            }
        }
    };

   
  
});